package util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * A DatabaseFile contains all of the records
 * that we have read in.  They are accessed
 * via offsets.  A DatabaseFile is capable of importing
 * other files using the CSVParser.
 * @author bfults (Brian Fults - 905084698)
 *
 */
public class DatabaseFile
{
    private RandomAccessFile file;
    private CSVFileParser parser;
    
    public DatabaseFile(String filePath) throws FileNotFoundException
    {
        file = new RandomAccessFile(filePath, "rw");
    }
    
    /**
     * imports records from a given CSV file.
     * @return A list of records, one for each imported
     * record.
     * @throws IOException 
     */
    public List<Record> importRecords(String csvFilePath) throws IOException
    {
        ArrayList<Record> records = new ArrayList<Record>();
        parser = new CSVFileParser(csvFilePath);
        while (parser.hasNext())
        {
            Record parsed = parser.nextRecord();
            addRecord(parsed);
            records.add(parsed);
        }
        parser.close();
        return records;
    }

    public Player getPlayer(long offset) throws IOException
    {
        Long currentOffset = file.getFilePointer();
        file.seek(offset);
        Player toReturn = CSVFileParser.createPlayer(file.readUTF());
        file.seek(currentOffset);
        return toReturn;
    }
    
    public void close() throws IOException
    {
        file.close();
    }
    /**
     * This method adds the record to this database file, and 
     * sets the record's offset to the file pointer's offset before
     * writing.
     * @param parsed
     * @throws IOException
     */
    private void addRecord(Record parsed) throws IOException
    {
        parsed.setOffset(file.getFilePointer());
        file.writeUTF(parsed.getLine());
    }
}
